package com.example.tcp.client.store.impl;

import com.example.tcp.client.RetryTcpClient;
import com.example.tcp.client.store.AbstractDequeStore;
import org.mapdb.*;

public class MapDBFileQueueDequeStore<T> extends AbstractDequeStore<T> {

    private DB db;
    private IndexTreeList<T> queue;

    public MapDBFileQueueDequeStore(String fileName, Serializer<T> serializer) {
        this.db = DBMaker.fileDB(fileName)
                .fileMmapEnable()
                .fileMmapEnableIfSupported()
                .cleanerHackEnable()
                .closeOnJvmShutdown()
                .executorEnable()
                .make();


       this.queue = db.indexTreeList("queue", serializer).createOrOpen();
    }

    @Override
    protected boolean _enqueue(T e) {
        return this.queue.add(e);
    }

    @Override
    protected T _dequeue() {
        return queue.removeAt(queue.getSize() - 1);
    }

    @Override
    protected void _close() {
        db.close();
    }

    @Override
    public boolean isEmpty() {
        return queue.isEmpty();
    }

    @Override
    public Object wrap() {
        return queue;
    }

    @Override
    public T peek() {
        return queue.get(queue.getSize() - 1);
    }

    @Override
    public long size() {
        return queue.size();
    }
}
